import { Context } from "koa";
import jwtUtils from "../utils/jwtUtils";
import logger from "../utils/logger";

/**
 * 路由的请求响应mid
 */
export async function routerResponseHandler(ctx: Context, data) {
  let message = '';
  // 如果data有errors属性 则为数据库throw的错误
  if (data?.errors) {
    message = (data?.errors as Array<any>)?.reduce((msg, err) => {
      msg += `${err.message}; `;
      return msg;
    }, '')
  }
  ctx.set('Cache-Control', 'no-cache');
  ctx.set('Content-Type', 'application/json');
  ctx.status = HttpStatus.OK;
  let responseData = message ? { status: 200, data: { dbErrorMsg: message } } : data;
  ctx.body = responseData;
};
/**
 * 错误响应handler
 */
export async function errorResponseHandler(ctx: Context, status: HttpStatus, error: string) {
  ctx.status = status;
  ctx.body = {
    status: status,
    data: {
      error
    }
  }
}
export enum HttpStatus {
  OK = 200,// 成功
  CREATE = 201,// 新增资源
  REDIRECT_PERMANENTLY = 301,// 永久重定向
  REDIRECT_TEMPORARY = 302,// 临时重定向
  NOT_MODIFIED = 304,// 资源未变化走本地缓存(配合If-Modified-Since头)
  BAD_REQUEST = 400,// 请求语法格式或参数错误
  UNAUTHORIZED = 401,// 请求方未授权,需要授权后才能请求资源
  FORBIDDEN = 403,// 请求方是未认证用户,服务器拒绝提供所请求的资源
  NOT_FOUND = 404,// 资源未找到
  METHOD_NOT_ALLOWED = 405,// 请求方法不允许
  INTERNAL_SERVER_ERROR = 500,// 服务器内部错误
  BAD_GATEWAY = 502,// 错误网关
  GATEWAY_TIMEOUT = 504// 网关超时
}